﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NWN.GDY.Service.Entity;
using NWN.GDY.Service.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;
using System.Data.Common;

namespace NWN.GDY.Service.DataAccess
{
    public class UserDA
    {
        public int RegisterUser(string uid, string psd)
        {
            int iOut = GDYConsts.ReturnDefine.UserExists;
            Database db = DatabaseFactory.CreateDatabase("GDYConnectionString");
            DbCommand dbCommand = db.GetStoredProcCommand("P_CreateUser");
            db.AddParameter(dbCommand, "@RETURN_VALUE", DbType.Int32, ParameterDirection.ReturnValue, null, DataRowVersion.Default, null);
            db.AddInParameter(dbCommand, "@UserID", DbType.String, uid);
            db.AddInParameter(dbCommand, "@UserPsd", DbType.String, psd);
            db.AddInParameter(dbCommand, "@InsertTime", DbType.DateTime, DateTime.Now);
            db.ExecuteNonQuery(dbCommand);
            iOut = (int)dbCommand.Parameters["@RETURN_VALUE"].Value;
            return iOut;
        }

        public int UserLogin(string uid, string psd)
        {
            int iOut = GDYConsts.ReturnDefine.InValidUser;
            Database db = DatabaseFactory.CreateDatabase("GDYConnectionString");
            DbCommand dbCommand = db.GetStoredProcCommand("P_ValidateUser");
            db.AddParameter(dbCommand, "@RETURN_VALUE", DbType.Int32, ParameterDirection.ReturnValue, null, DataRowVersion.Default, null);
            db.AddInParameter(dbCommand, "@UserID", DbType.String, uid);
            db.AddInParameter(dbCommand, "@UserPsd", DbType.String, psd);
            db.ExecuteNonQuery(dbCommand);
            iOut = (int)dbCommand.Parameters["@RETURN_VALUE"].Value;
            return iOut;
        }

        public User GetUser(string uid)
        { 
            User user = null;
            Database db = DatabaseFactory.CreateDatabase("GDYConnectionString");
            DbCommand dbCommand = db.GetSqlStringCommand("select * from tb_userinfo where userid=@userid");
            db.AddInParameter(dbCommand, "@userid", DbType.String, uid);
            using (IDataReader dr = db.ExecuteReader(dbCommand))
            {
                if (dr.Read())
                {
                    user = new User();
                    user.UserID = DBHelper.GetString(dr, "UserID");
                    user.NickName = DBHelper.GetString(dr, "NickName");
                }
            }
            return user;
        }
    }
}
